package com.maybach.core.msg.impl;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
import com.sun.jersey.core.util.MultivaluedMapImpl;
import org.apache.commons.lang.StringUtils;

import javax.ws.rs.core.MediaType;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by bleedfly on 15/7/28.
 */

public class LsmMsgService extends AbstractMsgService {

    public static String API = "key-ac2c1ea8eaa61e7ca617e17be7720b7f";

    public static String BASE_URL = "http://sms-api.luosimao.com/";

    public static String VERSION_NUM = "v1";

    public static String SEND_SMS_URL = BASE_URL + VERSION_NUM + "/send.json";

    @Override
    protected boolean valid(String target) {
        return this.isMobileNO(target);
    }

    @Override
    protected String sendMsg0(String mobile, String msg) {
        Client client = Client.create();
        client.addFilter(new HTTPBasicAuthFilter(
                "api", API));
        WebResource webResource = client.resource(
                SEND_SMS_URL);
        MultivaluedMapImpl formData = new MultivaluedMapImpl();
        formData.add("mobile", mobile);
        formData.add("message", msg);
        ClientResponse response = webResource.type(MediaType.APPLICATION_FORM_URLENCODED).
                post(ClientResponse.class, formData);
        String textEntity = response.getEntity(String.class);
        int status = response.getStatus();
        return textEntity;
    }



    /**
     * 是否是合法的手机号
     *
     * @param mobiles
     * @return
     */
    private  boolean isMobileNO(String mobiles) {
        if (StringUtils.isBlank(mobiles)) {
            return false;
        }
        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(14[57])|(17[0678])|(18[0,0-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }


}
